package com.acwer.drgs.performance.controller;

import com.acwer.common.RpnMsg;
import com.acwer.drgs.performance.config.ApplicationValues;
import com.acwer.drgs.performance.config.HttpUtils;
import com.acwer.drgs.performance.domain.EncodingUtil;
import com.acwer.drgs.performance.domain.RqGrp;
import com.acwer.drgs.performance.es.domain.MiniPerformanceInfo;
import com.acwer.drgs.performance.es.repo.MiniPerformanceRepo;
import com.acwer.drgs.performance.word.DefaultSummaryWord;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.ParsedComposite;
import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.ParsedCardinality;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.ParsedValueCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("pfm")
@Api(value = "pfm服务",tags = "绩效相关接口")
public class PfmController {


    @Autowired
    MiniPerformanceRepo performanceRepo;
    //分组器URL
    @Autowired
    ApplicationValues applicationValues;

    HttpUtils httpUtils = new HttpUtils();

    @ApiOperation("获取绩效明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页"),
            @ApiImplicitParam(name = "size",value = "每页大小"),
            @ApiImplicitParam(name = "s",value = "")
    })
    @GetMapping("ls")
    public RpnMsg<Page<MiniPerformanceInfo>> pfmls(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "") String s){

        NativeSearchQueryBuilder nQuery = new NativeSearchQueryBuilder();
        nQuery.withPageable(PageRequest.of(page-1,size));

        BoolQueryBuilder must= QueryBuilders.boolQuery();
        if(!StringUtils.isEmpty(s)){
            must.must(QueryBuilders.termQuery("bah.keyword",s));
        }
        nQuery.withQuery(must);

        Page<MiniPerformanceInfo> pageLs = performanceRepo.search(nQuery.build());

        return RpnMsg.SUCCESS(pageLs);
    }

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 获取出院病忘记
     * @param cpy
     * @return
     */
    @ApiOperation("获取出院病房（科室）")
    @ApiImplicitParam(value = "cpy",name = "单位名称")
    @GetMapping("bf")
    public RpnMsg zybf(@RequestParam(defaultValue = "") String cpy){

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
                .addAggregation(AggregationBuilders.terms("ls").size(1000).field("cybf.keyword"))
                .withPageable(PageRequest.of(0, 1));
        if(!StringUtils.isEmpty(cpy)){
            nativeSearchQueryBuilder.withQuery(QueryBuilders.termQuery("username.keyword",cpy));
        }
        SearchHits<MiniPerformanceInfo> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), MiniPerformanceInfo.class);
        Aggregation agge = search.getAggregations().get("ls");
        ParsedStringTerms terms=(ParsedStringTerms)agge;
        List<String> ls=new ArrayList<>();
        for (Terms.Bucket bucket : terms.getBuckets()) {
            ls.add(bucket.getKeyAsString());
        }
        return RpnMsg.SUCCESS(ls);
    }


    /**
     * 获取分组信息
     * @param ids
     * @return
     */
    @PostMapping("grp-info")
    public RpnMsg grp(String ids){
        RpnMsg rpnMsg = RpnMsg.SUCCESS();
        /*List<>*/
        List<Object> lst = new ArrayList<>();
        RqGrp rqGrp ;
        IdsQueryBuilder idsQueryBuilder = QueryBuilders.idsQuery().addIds(ids.split(","));
        Iterable<MiniPerformanceInfo> iterable = performanceRepo.search(idsQueryBuilder);
        for (MiniPerformanceInfo info : iterable) {
            rqGrp= new RqGrp();
            //主要诊断
            rqGrp.setMDCode(info.getJbdm());
            //其他诊断编码
            rqGrp.setODCodes(new ArrayList<String>(){
                {   if(info.getJbdm1()!=null){
                     add(info.getJbdm1());
                    }
                    if(info.getJbdm2()!=null){
                        add(info.getJbdm2());
                    }
                    if(info.getJbdm3()!=null){
                    add(info.getJbdm3());
                }
                    if(info.getJbdm4()!=null){
                        add(info.getJbdm4());
                }
                    if(info.getJbdm5()!=null){
                    add(info.getJbdm5());
                }
                    if(info.getJbdm6()!=null){
                    add(info.getJbdm6());
                }
                    if(info.getJbdm7()!=null){
                    add(info.getJbdm7());
                }
                    if(info.getJbdm8()!=null){
                    add(info.getJbdm8());
                }
                    if(info.getJbdm9()!=null){
                    add(info.getJbdm9());
                }
                    if(info.getJbdm10()!=null){
                    add(info.getJbdm10());
                }
                    if(info.getJbdm11()!=null){

                    add(info.getJbdm11());
                }
                    if(info.getJbdm12()!=null){
                    add(info.getJbdm12());
                }
                     if(info.getJbdm13()!=null){
                    add(info.getJbdm13());
                }
                    if(info.getJbdm14()!=null){
                        add(info.getJbdm14());
                    }
                    if(info.getJbdm15()!=null){
                        add(info.getJbdm15());
                    }
                }
               }
            );
            //主手术编码
            rqGrp.setMOpCode(info.getSsjczbm1());
            rqGrp.setOpCodes(new ArrayList<String>(){
                    {
                        if (info.getSsjczbm1()!=null) {

                            add(info.getSsjczbm1());

                        }
                        if (info.getSsjczbm2()!=null) {

                            add(info.getSsjczbm2());
                        }

                        if (info.getSsjczbm3()!=null) {

                            add(info.getSsjczbm3());
                        }

                        if (info.getSsjczbm4()!=null) {

                            add(info.getSsjczbm4());
                        }

                        if (info.getSsjczbm5()!=null) {

                            add(info.getSsjczbm5());
                        }

                        if (info.getSsjczbm6()!=null) {

                            add(info.getSsjczbm6());
                        }

                        if (info.getSsjczbm7()!=null) {

                            add(info.getSsjczbm7());
                        }

                    }
            });
            rqGrp.setAge(info.getNl());
            rqGrp.setGender(Integer.parseInt(info.getXb()));
            rqGrp.setAmount(info.getZfy());

            rqGrp.setBah(info.getBah());
            if(info.getXsecstz()!=0){
                //rqGrp.setNeoDay(info.getRysj()-info.getCsrq());
            }

            rqGrp.setNeoWeight(info.getXsecstz().toString());
            rqGrp.setNeoHosptWeight(info.getXserytz().toString());
            rqGrp.setLenOfStasy(Double.parseDouble(info.getSjzyts()));
            rqGrp.setLeaveWay(Integer.parseInt(info.getLyfs()));
            rqGrp.setIcd9Edition("1");
            rqGrp.setIcd10Edition("1");
            rqGrp.setDrgEdtion("CHSDRG");
            rqGrp.setUserName(info.getUsername());
            rqGrp.setBah(info.getBah());
            rqGrp.setGender(Integer.parseInt(info.getXb()));
            rqGrp.setUserName(info.getUsername());
            rqGrp.setMDCode(info.getJbdm());
            String jsonStr=JSON.toJSONString(rqGrp);
            System.out.println(jsonStr);
            RpnMsg rpnMsg1 =httpUtils.sendPost(jsonStr, applicationValues.getUri());
            lst.add(rpnMsg1.getData());
            System.out.println() ;


        }
        rpnMsg.setData(lst);
        return rpnMsg;
    }



//    @Autowired
//    ElasticsearchRestTemplate elasticsearchRestTemplate;


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class SimpleEsWhere{
        private String col;
        private String op;
        private Object val;
    }
    @ApiOperation("统计汇总")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time",value = "时间类型"),
            @ApiImplicitParam(name = "stime",dataType = "Integer",value = "开始日期(yyyyMMdd)"),
            @ApiImplicitParam(name = "etime",dataType = "Integer",value = "开始日期(yyyyMMdd)"),
            @ApiImplicitParam(name = "grp",value = "分组字段 默认值：grpinfo.mdc,grpinfo.name"),
            @ApiImplicitParam(name = "where",value = "查询条件：[{col:'ingrp',op:'eq',val:true},{col:'grpinfo.mdc',op:'lk',val:'mddc'}]"),
            @ApiImplicitParam(name = "sort",value = "如：_count-desc,weightSum-desc"),
            @ApiImplicitParam(name = "page",value = "当前页"),
            @ApiImplicitParam(name = "size",value = "每页大小")
    })
    @PostMapping("grpls")
    public RpnMsg grpls(
            @RequestParam(defaultValue = "rysj") String time,
            @RequestParam(defaultValue = "") String stime,
            @RequestParam(defaultValue = "") String etime,
            @RequestParam(defaultValue = "") String grp,
            @RequestParam(defaultValue = "") String where,
            @RequestParam(defaultValue = "") String sort,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size

    ){

        JSONObject o=defaultSummaryWord.innerGrpls(time,stime,etime,grp,where,sort,page,size);

        return RpnMsg.SUCCESS(o);
    }





    @Autowired
    DefaultSummaryWord defaultSummaryWord;

    @ApiOperation("生成word文档")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time",value = "时间类型"),
            @ApiImplicitParam(name = "stime",dataType = "Integer",value = "开始日期(yyyyMMdd)"),
            @ApiImplicitParam(name = "etime",dataType = "Integer",value = "开始日期(yyyyMMdd)")
    })

    @RequestMapping(
            method = {RequestMethod.GET,RequestMethod.POST},
            value = "gener-word"
    )
    public void generWord(
            String stime,
            String etime,
            String time,
            String cpy,
            HttpServletResponse repose){
        try {
            Map<String,Object>inps=new HashMap<String,Object>(){
                {
                    put("stime",stime);
                    put("etime",etime);
                    put("time",time);
                    put("cpy",cpy);
                }
            };
            defaultSummaryWord.genger(repose,inps);
        }catch (Exception e){
            e.printStackTrace();
        }
    }



}
